<template>
  <el-dialog :title="title" :visible.sync="dialogShow" @close="closeDialog">
    <!-- //!表单 -->
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="140px"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" type="textarea" rows="2" />
      </el-form-item>
      <el-row type="flex" justify="end">
        <el-button size="small" type="primary" @click="btnOk">确 定</el-button>
        <el-button size="small" @click="dialogShow = false">取 消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import { addRoleApi, editRoleApi, getRoleInfoApi } from '@/api/setting'
export default {
  name: 'AddRole',
  data() {
    return {
      dialogShow: false,
      formData: {
        name: '',
        description: ''
      },
      formRules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        description: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑' : '新增'
    }
  },
  methods: {
    // 表单提交事件
    async btnOk() {
      // 1.表单校验
      try {
        await this.$refs.form.validate()
      } catch (e) {
        return console.log(e)
      }
      // 2.发送请求
      // 3.成功提示
      if (this.formData.id) {
        await editRoleApi(this.formData)
        this.$message.success('修改成功')
      } else {
        await addRoleApi(this.formData)
        this.$message.success('新增成功')
      }

      // 4.列表更新
      this.$emit('updateList')
      // 5.关闭弹框
      this.dialogShow = false
    },
    // 重置表单
    closeDialog() {
      this.formData = {
        name: '',
        description: ''
      }
    },
    // 获取回显数据
    async getRoleInfo(id) {
      // 获取修改行完整的数据
      const res = await getRoleInfoApi(id)
      console.log(res)
      // 回显表单
      this.formData = res
      // 弹框打开
      this.dialogShow = true
    }
  }
}
</script>

<style></style>
